package com.woniuedu.search.direct;

import com.alibaba.fastjson.JSONObject;
import com.rabbitmq.client.Channel;
import com.woniuedu.search.entity.Article;
import com.woniuedu.search.entity.Course;
import com.woniuedu.search.entity.Messages;
import com.woniuedu.search.entity.Teacher;
import com.woniuedu.search.serviec.ArticleService;
import com.woniuedu.search.serviec.CourseService;
import com.woniuedu.search.serviec.TeacherService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.io.IOException;
@Slf4j
@Component
public class DelRecevier {
    @Resource
    private TeacherService teacherService;
    @Resource
    private ArticleService articleService;
    @Resource
    private CourseService courseService;
    // 接收生产者发送的消息
    @RabbitListener(queues = "direct_del")  // 监听消息队列
    public void accept(Message message, Channel channel){
        try {
            log.info("业务代码执行中...."+message.getPayload());
            Messages messages=(Messages) message.getPayload();
            log.info("队列queue_demo01收到消息:" + messages.getMsgData());
            if("teacher".equals(messages.getType())){
                Teacher teacher=JSONObject.parseObject(messages.getMsgData(),Teacher.class);
                teacherService.deleteById(teacher.getId());
            } else if("article".equals(messages.getType())){
                Article article=JSONObject.parseObject(messages.getMsgData(),Article.class);
                articleService.deleteById((article).getId());
            } else if("course".equals(messages.getType())){
                Course course=JSONObject.parseObject(messages.getMsgData(),Course.class);
                courseService.deleteById((course).getId());
            }else {
                channel.basicNack((Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG),false,false);
            }
            channel.basicAck((Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG), false);
        } catch (Exception e) {
            log.info("消息消费失败");
            try {
                // 丢弃消息
                channel.basicNack((Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG),false,false);
            }  catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
